package com.lm.upms.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lm.common.core.util.R;
import com.lm.upms.api.entity.SysMenu;
import com.lm.upms.api.entity.SysRoleMenu;
import com.lm.upms.api.vo.MenuVO;
import com.lm.upms.mapper.SysMenuMapper;
import com.lm.upms.service.SysMenuService;
import com.lm.upms.service.SysRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 菜单
 *
 * @author lm
 * @date
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Override
    public List<MenuVO> findMenuByRoleId(Integer roleId) {
        return baseMapper.listMenusByRoleId(roleId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R removeMenuById(Integer id) {
        // 查询父节点为当前节点的节点
        List<SysMenu> menuList = this.list(Wrappers.<SysMenu>query().lambda().eq(SysMenu::getParentId, id));
        if (CollUtil.isNotEmpty(menuList)) {
            return R.error("菜单含有下级不能删除！");
        }

        sysRoleMenuService.remove(Wrappers.<SysRoleMenu>query().lambda().eq(SysRoleMenu::getMenuId, id));

        // 删除当前菜单及其子菜单
        return R.success(this.removeById(id));
    }

    @Override
    public Boolean updateMenuById(SysMenu sysMenu) {
        return this.updateById(sysMenu);
    }

    @Override
    public Set<Integer> selectMenuIdsByRoleId(Integer roleId) {
        List<Integer> menuIds = baseMapper.listMenusByRoleId(roleId)
                .stream()
                .map(MenuVO::getMenuId)
                .collect(Collectors.toList());
        Set<Integer> idsSet = new HashSet<>(menuIds);
        return idsSet;
    }

}
